package org.smart4j.aopdemo.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.smart4j.aopdemo.simple.Greeting;
import org.smart4j.aopdemo.simple.GreetingImpl;

import java.lang.reflect.Method;

public class CGLibProxy implements MethodInterceptor {

    public <T> T getProxy(Class<T> cls) {
        return (T) Enhancer.create(cls, this);
    }

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before();
        Object result = methodProxy.invokeSuper(o, objects);
        after();
        return result;
    }

    public void before() {
        System.out.println(" before Hello ");
    }

    public void after() {
        System.out.println(" after Hello");
    }

    public static void main(String[] args) {
        CGLibProxy cgLibProxy = new CGLibProxy();
        Greeting greeting = cgLibProxy.getProxy(GreetingImpl.class);
        greeting.sayHello("liuzx");
    }
}
